<template>
    <!-- 群聊里点击更多操作弹出的组件 -->
    <div class="group-panel">
        <el-drawer v-model="showDrawer" modal-class="mask-style" :size="300" ref="drawerRef">
            <div class="group-panel-body">
                <div class="member-list">
                    <div class="member-item" v-for="(item, index) in memberList" :key="index">
                        <!-- 头像 -->
                        <Avatar :userId="item.userId" :width="30" @closeDrawer="closeDrawerHandler"></Avatar>
                        <!-- 名字 -->
                        <div class="nick-name" :title="item.userName">{{ item.userName }}</div>
                        <!-- 群主标记 -->
                        <div class="owner-tag" v-if="item.userId == groupInfo.groupOwnerId">群主</div>
                    </div>
                    <template v-if="userInfoStore.getUserInfo().userId == groupInfo.groupOwnerId">
                        <!-- 群成员操作 -->
                        <div class="member-item" @click="addUser">
                            <div class="iconfont icon-tianjia- icon-op"></div>
                            <div class="nick-name">添加</div>
                        </div>
                        <div class="member-item" @click="removeUser">
                            <div class="iconfont icon-shanchu2-L icon-op"></div>
                            <div class="nick-name">移除</div>
                        </div>
                    </template>
                </div>
                <!-- 群聊信息 -->
                <div class="line"></div>
                <div class="part-content">
                    <AvatarBase :userId="groupInfo.groupId" :width="60" :borderRadius="5" :showDetail="true">
                    </AvatarBase>
                </div>
                <div class="part-title">群号</div>
                <div class="part-content">{{ groupInfo.groupId }}</div>
                <div class="part-title">群聊名称</div>
                <div class="part-content">{{ groupInfo.groupName }}</div>
                <div class="part-title">群公告</div>
                <div class="part-content">{{ groupInfo.groupNotice || '-' }}</div>
                <div class="line"></div>
                <a href="javascript:void(0)" class="leave-btn" @click="disbandGroup"
                    v-if="userInfoStore.getUserInfo().userId == groupInfo.groupOwnerId">解散群聊</a>
                <a href="javascript:void(0)" class="leave-btn" @click="leaveGroup" v-else>退出群聊</a>
            </div>
        </el-drawer>
    </div>
    <UserSelect ref="userSelectRef" @callback="addOrRemoveUserCallback"></UserSelect>
</template>

<script setup>
import UserSelect from "./UserSelect.vue";

import AvatarBase from "@/components/AvatarBase.vue";
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue"
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

import { useUserInfoStore } from '@/stores/UserInfoStore'
const userInfoStore = useUserInfoStore();
import { useContactStateStore } from "@/stores/ContactStateStore"
const contactStateStore = useContactStateStore();

const showDrawer = ref(false);
const memberList = ref([]);
const groupInfo = ref({});

const show = async (groupId) => {
    let result = await proxy.Request({
        method: "get",
        url: proxy.Api.getGroupInfo4Chat,
        params: {
            groupId
        },
        showError: false,
        errorCallback: (response) => {
            proxy.Confirm({
                message: response.info,
                showCancelBtn: false
            })
        }
    })
    if (!result) {
        return;
    }
    showDrawer.value = true;
    memberList.value = result.data.userContactList;
    groupInfo.value = result.data.groupInfo;
}

/* 让外部调用打开 */
defineExpose({
    show
});

const drawerRef = ref(null);
const closeDrawerHandler = () => {
    // drawerRef.value?.closeDrawer();
}

const userSelectRef = ref(null);

const addUser = async () => {
    // 获取群主的好友列表，从当中选择
    let result = await proxy.Request({
        url: proxy.Api.loadContact,
        params: {
            contactType: 'USER'
        }
    })
    if (!result) {
        return
    }
    const contactIds = memberList.value.map((item) => item['userId'])
    let contactList = result.data
    // 过滤掉已经存在的用户
    contactList.forEach((element) => {
        if (contactIds.includes(element.userId)) {
            element.disabled = true
        }
    })
    // 调用transfer组件
    userSelectRef.value.show({
        contactList,
        groupId: groupInfo.value.groupId,
        opType: "ADD"
    })
}
const removeUser = () => {
    let contactList = memberList.value.map((item) => item)
    contactList.splice(0, 1)  // 去除群主自己
    userSelectRef.value.show({
        contactList,
        groupId: groupInfo.value.groupId,
        opType: "REMOVE"
    })
};

const addOrRemoveUserCallback = () => {
    showDrawer.value = false;
}

const emit = defineEmits(['delChatSession']);
const leaveGroup = () => {
    proxy.Confirm({
        message: `确定要退出群聊【${groupInfo.value.groupName}】吗？`,
        showCancelBtn: true,
        okFun: async () => {
            // 提示父组件更新会话列表
            let result = await proxy.Request({
                method: "post",
                url: proxy.Api.leaveGroup,
                params: {
                    groupId: groupInfo.value.groupId
                }
            })
            if (!result) {
                return;
            }
            proxy.Message.success("退出群聊成功")
            // 关闭本组件后，通知父组件刷新会话列表（删除会话的操作也包含在父组件的回调函数里了）
            showDrawer.value = false;
            emit('delChatSession', { contactId: groupInfo.value.groupId })
        }
    })
}
const disbandGroup = () => {
    proxy.Confirm({
        message: `确定要解散群聊【${groupInfo.value.groupName}】吗？`,
        showCancelBtn: true,
        okFun: async () => {
            let result = await proxy.Request({
                method: "delete",
                url: proxy.Api.disbandGroup,
                params: {
                    groupId: groupInfo.value.groupId
                }
            })
            if (!result) {
                return;
            }
            proxy.Message.success("解散群聊成功")
            showDrawer.value = false;
        }
    })
} 
</script>

<style lang="scss" scoped>
.group-panel {
    color: #000000;

    :deep(.mask-style) {
        top: 1px;
        right: 1px;
        height: calc(100vh - 2px);
    }

    :deep(.el-drawer) {
        -webkit-app-region: no-drag;
    }

    :deep(.el-drawer__header) {
        margin-bottom: 10px;
    }

    :deep(.el-drawer__body) {
        padding: 10px;
    }

    .group-panel-body {
        .member-list {
            display: flex;
            flex-wrap: wrap;

            .member-item {
                width: 20%;
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-bottom: 5px;
                padding: 5px;
                position: relative;

                .owner-tag {
                    position: absolute;
                    left: 0px;
                    top: 0px;
                    font-size: 12px;
                    background: #08a1cf;
                    color: #fff;
                    border-radius: 3px;
                }

                .nick-name {
                    margin-top: 3px;
                    width: 100%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    font-size: 13px;
                    text-align: center;
                }

                .icon-op {
                    cursor: pointer;
                    width: 30px;
                    height: 30px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border: 1px solid #dbdbdb;
                    color: #6e6e6e;
                }
            }
        }

        .line {
            margin-bottom: 10px;
            border-top: 1px solid #ddd;
            height: 1px;
        }

        .part-title {
            margin-top: 10px;
        }

        .part-content {
            color: #757575;
            margin-bottom: 10px;
        }

        .leave-btn {
            color: #f45454;
            text-decoration: none;
            text-align: center;
            display: block;
            margin-top: 10px;
        }
    }
}
</style>